<?php
namespace app\admin\controller;

use think\File;
use think\Db;
use utils\BackUp;
use utils\Auth;

class Admin extends Base {

    public function index() {
        $this->view->engine->layout(true);

        $version = Db::query('select version() as ver');

        $this->assign('mysqlVersion', $version[0]['ver']);
        return $this->fetch();
    }

    public function customer_list() {
        $this->view->engine->layout(true);

        $condition = input('condition');
        $condition_str = str2where($condition);
        $where = '1 = 1';
        if ($condition_str) {
            $where = $condition_str;
        }
        $this->assign('condition', $condition);


        $customerList = db('customer')
            ->where($where)
            ->paginate(10);

        $this->assign('customerList', $customerList);

        return $this->fetch();
    }

    public function customer_edit() {
        $this->view->engine->layout(true);

        $id = input('id/d');

        if ($id) {
            $customer = db('customer')->alias('c')
                ->where('id', $id)
                ->find();

            $this->assign('customer', $customer);
        }

        return $this->fetch();
    }

    public function customer_save() {
        $data = input();

        $validate = validate('Customer');
        $id         = input('id/d');
        $real_name  = input('real_name');
        $sex        = input('sex/d');
        $birthday   = input('birthday');
        $addr       = input('addr');
        $phone      = input('phone');
        $mobile     = input('mobile');
        $balance    = input('balance');
        $remark     = input('remark');

        $updateData = [
            'real_name'  => $real_name,
            'phone'      => $phone,
            'mobile'     => $mobile,
            'addr'       => $addr,
            'sex'        => $sex,
            'birthday'   => $birthday,
            'balance'    => $balance,
            'remark'     => $remark
        ];

        if ($id) {
            if (!$validate->scene('updateCustomer')->check($data)) {
                return $this->error($validate->getError());
            }
            
            db('customer')->where('id', $id)->update($updateData);
            op($this->manager['id'], '修改会员', '管理员[' . $this->manager['name'] . ']:修改了会员 ' . $real_name . ' 的信息, 消费金额: ' . $balance, $id);
        } else {
            if (!$validate->scene('insertCustomer')->check($data)) {
                return $this->error($validate->getError());
            }

            if (!$validate->scene('birthdayVerify')->check($birthday)) {
                $birthday = date('Y-m-d');
            }

            $updateData['reg_time'] = date('Y-m-d H:i:s');
            $customer_id = db('customer')->insertGetId($updateData);
            op($this->manager['id'], '添加会员', '管理员[' . $this->manager['name'] . ']:添加了会员 ' . $real_name . ' 的信息, 消费金额: ' . $balance, $customer_id);
        }
        return $this->success('更新成功', 'customer_list', [], 1);
    }

    public function customer_del() {
        $id = input('id/a');
        
        if ($id) {
            $users = db('customer')->where('id', 'in', $id)->select();
            db('customer')->where('id', 'in', $id)->delete();
            if ($users) {
                $user_names = '';
                foreach ($users as $user) {
                    $user_names .= $user['real_name'] . '、';
                }

                $user_names = trim($user_names, '、');
                op($this->manager['id'], '删除会员', '管理员[' . $this->manager['name'] . ']:删除了会员 ' . $user_names, 0);
            }
            
            return $this->success('删除成功', 'customer_list', [], 1);
        }
        return $this->error('没有可删除的用户');
    }

    public function customer_jf() {
        $customer_id = input('id');
        $status = input('status');
        $point = input('point');
        $remark = input('remark');
        $real_name = input('real_name');

        $customerInfo = db('customer')->where('id', $customer_id)->find();
        if ($customerInfo) {
            if ($status == 'add') {
                $currentPoint = $point + $customerInfo['point'];
                db('customer')->where('id', $customer_id)->setInc('point', $point);
                op($this->manager['id'], '增加积分', '管理员[' . $this->manager['name'] . ']:给 ' . $real_name . ' 会员增加了: ' . $point . '积分, 原积分' . $customerInfo['point'] . ', 现有积分: ' . $currentPoint . ', 备注' . $remark, $customer_id, 'point');
            } elseif ($status == 'cut') {
                if ($customerInfo['point'] < $point) {
                    return $this->error('操作失败，被减后的积分不能为负数');
                }
                $currentPoint = $customerInfo['point'] - $point;
                db('customer')->where('id', $customer_id)->setDec('point', $point);
                op($this->manager['id'], '增加积分', '管理员[' . $this->manager['name'] . ']:给 ' . $real_name . ' 会员减少了: ' . $point . '积分, 原积分' . $customerInfo['point'] . ', 现有积分: ' . $currentPoint . ', 备注' . $remark, $customer_id, 'point');
            }
            return $this->success('操作成功', 'customer_list', [], 1);
        } else {
            return $this->error('该用户不存在');
        }
    }

    public function log_operation_list() {
        $this->view->engine->layout(true);

        $searchType = input('searchType');
        if ($searchType) {
            if ($searchType == 'all') {
                $where = '1 = 1';
            } else {
                $where = ['lo.customer_id' => $searchType];
            }

            $this->assign('searchType', $searchType);
        } else {
            $where = '1 = 1';
        }

        $customerList = db('customer')->field('id, real_name')->select();
        $this->assign('customerList', $customerList);

        $logOperationList = db('log_operation')->alias('lo')
            ->field('lo.*,ma.name as mname')
            ->join('manager ma', 'lo.manager_id = ma.id', 'LEFT')
            ->where($where)
            ->order('lo.id desc')
            ->paginate(10);

        $this->assign('logOperationList', $logOperationList);

        return $this->fetch();
    }

    public function log_operation_del() {
        $id = input('id/a');

        if ($id) {
            db('log_operation')->where('id', 'in', $id)->delete();
        }

        return $this->success('删除成功', 'log_operation_list', [], 1);
    }

    public function jf_detail() {
        $this->view->engine->layout('layout/blank');
        $customer_id = input('id');

        $logOperationList = db('log_operation')->alias('lo')
            ->field('lo.*,ma.name as mname')
            ->join('manager ma', 'lo.manager_id = ma.id', 'LEFT')
            ->where('lo.customer_id', $customer_id)
            ->where('lo.type', 'point')
            ->order('lo.id desc')
            ->paginate(10);

        $this->assign('logOperationList', $logOperationList);

        return $this->fetch();
    }

    public function login() {
        return $this->fetch();
    }

    public function check() {
        $data = input('');

        $validate = validate('Login');
        if (!$validate->scene('loginCheck')->check($data)) {
            return $this->error($validate->getError());
        }

        $manager = db('manager')->where('name', $data['username'])->find();
        if ($manager) {
            $key = md5($manager['validcode']);
            $password = substr($key, 0, 16) . $data['password'] . substr($key, 16, 16);
            if ($manager['password'] == md5($password)) {
                session('manager', $manager);

                db('manager')->where('id', $manager['id'])->update([
                    'last_ip' => request()->ip(),
                    'last_login' => date('Y-m-d H:i:s')
                ]);

                return $this->redirect('admin/index');
            }
        }

        return $this->success('登录失败，请检查用户密码');
    }

    public function logout() {
        session('manager', null);

        return $this->redirect('admin/login');
    }
}